import fs from "node:fs";
import path from "node:path";
import { resolveVuePathMap } from "./ResolveVueModule.js";

function CompilerSFC({ app, root }) {
  app.use(async (ctx, next) => {
    await next();
    // 判断是否为vue文件
    if (ctx.path.endsWith(".vue")) {
      if (ctx.query.type !== "style") {
        const filePath = path.join(root, ctx.path.slice(1));
        // 获取.vue文件内容
        const code = fs.readFileSync(filePath, "utf8");
        // 读取解析.vue文件的处理器
        const { compilerSFC } = resolveVuePathMap(root);
        const { parse, compileTemplate } = await import(
          "file://" + compilerSFC
        );
        const {
          descriptor: { template, script, styles },
        } = parse(code);

        let codeTotal = ``;
        // 解析js
        if (script) {
          const scriptContent = script.content.replace(
            "export default",
            "const __sfc_main = "
          );
          codeTotal += scriptContent;
        }
        // 解析template
        if (template) {
          const templateContent = compileTemplate(template).code;
          codeTotal += templateContent;
          codeTotal += `\n __sfc_main.render = render`;
          codeTotal += `\n export default __sfc_main`;
        }

        // 处理style
        if (styles) {
          let styleContent = "";
          styles.forEach((style) => {
            styleContent += style.content;
          });
          codeTotal += `\n import updateStyle from "${ctx.path}?type=style"`;
          codeTotal += `\n  updateStyle(${JSON.stringify(styleContent)})`;
        }
        ctx.type = "js";
        ctx.body = codeTotal;
      }
    }
  });
}

export default CompilerSFC;
